import asyncio
import json

from config import CMD_PING
from log import info
from tcp_server import TcpServer
from tcp_client import TcpClient


async def main():
    # 启动服务端（监听 ESP32）
    server = TcpServer(port=8765)
    asyncio.create_task(server.start())

    # 模拟主动推送（例如：更新屏幕内容）
    await asyncio.sleep(5)
    info("[Main]   向所有 server 推送消息")
    await server.broadcast(json.dumps({"cmd": "hello", "data": "Hello server!"}))

    # 模拟客户端连接（仅用于测试）
    client = TcpClient("127.0.0.1", 8765)
    await client.connect()
    asyncio.create_task(client.listen())

    await asyncio.sleep(2)
    await client.send({"cmd": CMD_PING})

    # 一直运行
    await asyncio.sleep(9999)


if __name__ == "__main__":
    asyncio.run(main())